package cn.lei.netty.herostory.cmdhandler;

import cn.lei.netty.herostory.login.LoginService;
import cn.lei.netty.herostory.model.User;
import cn.lei.netty.herostory.model.UserManager;
import cn.lei.netty.herostory.msg.GameMsgProtocol;
import io.netty.channel.ChannelHandlerContext;
import io.netty.util.AttributeKey;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 用户登录
 *
 * @author lei
 */
public class UserLoginCmdHandler implements ICmdHandler<GameMsgProtocol.UserLoginCmd> {
    /**
     * 日志对象
     */
    static private final Logger LOGGER = LoggerFactory.getLogger(UserLoginCmdHandler.class);
    @Override
    public void handle(ChannelHandlerContext ctx, GameMsgProtocol.UserLoginCmd cmd) {
        if (ctx == null || cmd == null) {
            return;
        }
        String userName = cmd.getUserName();
        String password = cmd.getPassword();

        if (userName == null || password == null) {
            return;
        }

        LOGGER.info("当前线程 = {}",Thread.currentThread().getName());

        //获取用户实体
       LoginService.getInstance().userLogin(userName, password,(userEntity)->{
           GameMsgProtocol.UserLoginResult.Builder loginBuilder = GameMsgProtocol.UserLoginResult.newBuilder();

           LOGGER.info("当前线程 = {}",Thread.currentThread().getName());

           if (userEntity == null) {
               loginBuilder.setUserId(-1);
               loginBuilder.setUserName("");
               loginBuilder.setHeroAvatar("");
           } else {
               User newUser = new User();
               newUser.userId = userEntity.userId;
               newUser.userName = userEntity.userName;
               newUser.heroAvatar = userEntity.heroAvatar;
               newUser.currHp = 100;
               UserManager.addUser(newUser);

               //用户ID 保存至 Session
               ctx.channel().attr(AttributeKey.valueOf("userId")).set(newUser.userId);

               loginBuilder.setUserId(userEntity.userId);
               loginBuilder.setUserName(userEntity.userName);
               loginBuilder.setHeroAvatar(userEntity.heroAvatar);
           }

           GameMsgProtocol.UserLoginResult newResult = loginBuilder.build();
           ctx.writeAndFlush(newResult);
           return  null;
        });
    }
}
